package com.service.impl;

import com.dao.BusinessMapper;
import com.dao.CartMapper;
import com.dao.OrderdetailetMapper;
import com.dao.OrdersMapper;
import com.model.Business;
import com.model.Cart;
import com.model.Orders;
import com.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper mapper;
    @Autowired
    private CartMapper cartmapper;
    @Autowired
    private BusinessMapper businessmapper;
    @Autowired
    private OrderdetailetMapper orderdetailetmapper;
    @Override
    public int createOrders(String userId, int businessId, int daId) {
        double orderTotal = 0;
        int orderId = -1;
        try {
            //1、查询当前用户购物车中当前商家的所有食品
            List<Cart> carts = cartmapper.listCart(userId, businessId);
            //2、查询商家信息（需要使用商家的配送费信息）
            Business business = businessmapper.getBusinessById(businessId);
            //3、获取订单总额
            for (Cart cart : carts) {
                orderTotal += cart.getFood().getFoodPrice() * cart.getQuantity();
            }
            //加上配送费
            orderTotal += business.getDeliveryPrice();
            //3、创建订单，并获取订单编号
            orderId = mapper.createOrders(userId, businessId, daId, orderTotal);
            //4、处理相关数据：获取订单明细集合
            //5、批量添加订单明细
            for (Cart cart : carts) {
                orderdetailetmapper.saveOrderdetailet(cart.getFoodId(), orderId, cart.getQuantity());
            }
            //6、清空当前用户购物车中当前商家的所有食品
            cartmapper.removeCart1(userId, businessId);
        } catch (Exception e) {
            orderId = 0;
            e.printStackTrace();
        }
        return orderId;
    }


    @Override
    public Orders getOrdersById(int orderId) {
        Orders orders = new Orders();
        try {
            orders = mapper.getOrdersById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        List<Orders> list = new ArrayList<>();
        try {
            list = mapper.listOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
